<?php

namespace api\modules\v1\models;

use api\func\func;
use Yii;
use api\common\models\Common;
use yii\base\Exception;
use yii\web\NotFoundHttpException;
use yii\web\HttpException;
use yii\data\ActiveDataProvider;
use api\modules\v1\models\News;
use api\common\controllers\CommonController;
use api\common\models\Mar;
use yii\data\Pagination;
use yii\web\Link;
use \yii\db\Query;
class Collect extends Common
{

    /**
     * @return array|string
     */
    public static function tableName()
    {
        return '{{%collect_app}}';
    }


    public function rules()
    {
        return [
            ['uid', 'required','message'=>'用户ID不能为空'],

            ['catid', 'required','message'=>'分类ID不能为空'],
            ['catid', 'integer'],

            ['content_id', 'required','message'=>'内容ID不能为空'],
            ['content_id', 'integer'],
            ['content_id', 'validateContent'],
        ];
    }

    /*
     * 验证文章是否存在
     * @param $attribute
     * @param $params
     * @return bool
     */
    public function validateContent($attribute, $params)
    {
        $news_table = '{{%'.News::getTable($this->catid).'}}';
        $news_model = new Mar($news_table);
        if(!$news_model->findOne(['id'=>$this->content_id])){
            $this->addError($attribute, '未找到文章信息content_id');
        }
        return true;
    }

    /*
     * 获取收藏列表
     */
    public function getList(){
        $data = self::find()->select('GROUP_CONCAT(content_id) AS content_id,catid,time')
            ->where('uid=:uid',[':uid'=>Yii::$app->user->identity->id])
            ->groupBy('catid')
            ->asArray()
            ->orderBy('time desc')
            ->all();
        $fields = 'id,catid,title,thumb,keywords,description,username,inputtime,updatetime,like,comment,zst,thirdid';
        if(count($data) >0 ){
            $query = (new Query())
                ->select($fields)
                ->where('id in ('.$data[0]['content_id'].') and `status` = 99')
                ->from('{{%'.News::getTable($data[0]['catid']).'}}');
            unset($data[0]);


            foreach($data as $key=>$value){
                $query->union((new Query())
                    ->select($fields)
                    ->where('id in ('.$value['content_id'].') and `status` = 99')
                    ->from('{{%'.News::getTable($value['catid']).'}}'),true);
            }

            $query = (new Query())->from(['tmpA'=>$query]);
        }else{
            $query = self::find()->where(['id'=>0]);
        }
        $count = $query->count();

        $pagination = new Pagination(['totalCount' => $count]);
        $pagination->defaultPageSize = Yii::$app->params['page_size'];

        $data = $query->offset($pagination->offset)
            ->limit($pagination->limit)
            ->all();

        $this->serializePagination($pagination);

        $ImgBaseUrl = self::getImgBaseUrl();
        foreach($data as $key=>$value){
            /**
            if($value['thumb'] !=''){
                $data[$key]['thumb'] = $ImgBaseUrl.$value['thumb'];
            }
            */

            if($value['zst'] !=''){
                $zst = [];
                $zst_tmp = json_decode($value['zst'],1);
                foreach($zst_tmp as $v){
                    $zst[] = $v['url'];
                }
                $data[$key]['zst'] = $zst;
            }else{
                $data[$key]['zst'] = [];
            }

            $comment_num = Comment::find()->where("pid = 0 and top_pid = 0 and content_id = {$value['id']} and catid = {$value['catid']} and status =1")->count();
            $data[$key]['comment'] = $comment_num;
        }

        $_data = [];
        $_data['items'] = $data;
        $_data['_links'] = $this->linksEnvelope;
        $_data['_meta'] = $this->metaEnvelope;


        //echo $query->createCommand()->getRawSql();exit;
        return $_data;
    }

    /*
     * 统计系统推送
     * @param int $is_canel
     * @throws NotFoundHttpException
     */
    public function PushTj($content_id,$catid,$is_canel=1){
        try{
            $news_data = News::getInfoSim($content_id,$catid);
            if($news_data['thirdid'] =='' || $news_data['thirdid'] == 0) return true;
            $user = func::IdToUser($news_data['thirdid']);
            $nickname = $user->nickname != '' ? $user->nickname :func::replace_phone($user->phone);
            $phone = $user->phone;
            $data = '{"User_id":'.Yii::$app->user->identity->id.',"Article_id":'.$content_id.',"Article_type":'.$catid.',"Is_cancel":'.$is_canel.',"Collection_time":"'.date('Y-m-d H:i:s').'","Article_title":"'.$news_data['title'].'","Nickname":"'.$nickname.'","Phone":'.$phone.'}';
            $data = array('data' => $data,'key'=>'c3RhdGlzdGlj');
            $json = func::GoCurl('/api/collection/insert',  'POST',$data, $error_msg);
            $array = json_decode($json, true);
            if($array['Code'] != 10000){

            }
        }catch (Exception $e){}
    }
}
